import 'dart:async';

import 'package:gold/app/order_event.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_order.dart';
import 'package:gold/http/http.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_extension.dart';

/// @description: 商品支付状态
/// @author tangzhentao
/// @created at 22:39 2025/2/15

class PayViewmodel extends Viewmodel {
  /// 订单id
  final int id;
  /// 订单类型 商品，黄金投资，积分
  final String type;
  /// 是否来自订单
  final bool fromOrder;
  /// 订单创建时间
  final String? createAt;

  bool _isWechat = true;
  /// 是否微信支付
  bool get isWechat => _isWechat;

  int _payTime = 15 * 60;
  /// 支付倒计时
  int get payTime => _payTime;
  /// 计时器
  Timer? _timer;

  PayViewmodel(this.id, this.type, this.fromOrder, this.createAt) {
    _startTimer();
  }

  /// 修改支付方式
  void changeType() {
    _isWechat = !_isWechat;
    notifyListeners();
  }

  /// 确认支付
  Future confirmPay() async {
    if (_payTime == 0) {
      '订单已过期'.info();
      return;
    }
    final result = await Http().request<dynamic>(ApiOrder.testPay, loadingText: '支付中...', data: {'id': id});
    if (result.success) {
      final data = {'type': type, 'id': id, 'fromOrder': fromOrder};
      if (fromOrder) {
        XfgNav.eventBus.fire(PayingOrderResult(id, true));
        XfgNav.pushReplacementNamed(Routes.paySuccess, arguments: data);
      } else {
        XfgNav.pushNamedAndRemoveUntil(Routes.paySuccess, routeName: Routes.root, arguments: data);
      }
    }
  }

  /// 启动计时器
  void _startTimer() {
    if (createAt?.isNotEmpty == true) {
      final date = DateTime.tryParse(createAt!);
      if (date != null) {
        final second = (DateTime.now().millisecondsSinceEpoch - date.millisecondsSinceEpoch) ~/ 1000;
        _payTime = second;
      }
    }
    if (_payTime > 0) {
      _timer = Timer.periodic(const Duration(seconds: 1), (_) {
        _payTime--;
        notifyListeners();
        if (_payTime == 0) _cancelTimer();
      });
    }
  }

  /// 停止计时器
  void _cancelTimer() {
    _timer?.cancel();
    _timer = null;
  }

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }
}
